/*
 * @Description: url模块
 * @Author: Haor
 * @Date: 2022-02-22 09:01:24
 * @LastEditTime: 2022-04-28 20:26:12
 * @LastEditors: Haor
 */

/**
 * url参数序列化
 * @param {String} url
 * @param {Object} extParams
 */
export const urlSerialize = (url = '', extParams = {}) => {
    const params = {
        ...getQueryParams(url), // 原始数据
        ...extParams
    }

    // 组装后的新参数
    const queryStr = Object.keys(params).reduce((pre, key) => {
        pre += [key, params[key] || '']
        return pre
    }, '')
    const paramsUrl = `${url.split('?')[0]}?${queryStr}`
    return paramsUrl
}

/**
 * 获取query参数
 * @param {String} url
 * @return {Object}
 */
export const getQueryParams = (url = '') => {
    const [, params] = url.split('?')
    if (!params) {
        return null
    }
    return params.split('&').reduce((pre, param) => {
        const [key, val] = param.split('=')
        pre[key] = Number.isNaN(Number(val)) ? val : Number(val)
        return pre
    }, {})
}
